package com.project.nimsen.web.pub.tag;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Component;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dto.ColfileDto;
import com.project.nimsen.entity.Coltype;
import com.project.nimsen.service.IColfileService;
import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.util.NimsenUtil;
import com.project.nimsen.util.WebUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
 * 用于得到一个栏目的信息
 * */
@Component("nimsen_column")
public class ColumnTag extends BaseTag {
	@Resource
	IColtypeService coltypeService;
	@Resource
	IColfileService colfileService;
	/**
	 * @param number 栏目编号，如果是PARENT则表示为当前栏目的父栏目
	 * 						OWNER则表示为当前栏目。其他为栏目的
	 * 						信息，不可以为空
	 * @param field 属性名称 其中colname代表栏目名，vurl代表访问的url
	 * 				,microimgurl代表栏目的缩略图,不可以为空
	 * */
	public void exec(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		String number = getParam("number");
		String field = getParam("field");
		//判断两个参数是否为null值
		if(StringUtils.isBlank(number)||StringUtils.isBlank(field))
			return;
		Coltype curcol = null;
		try {
			//siteid
			String siteid = getSessionAttr("pub_siteid");
			String colid = getAttr("coltypeid");
			if("OWNER".equals(number)){
				curcol = coltypeService.findEntityById(colid);
			}else if("PARENT".equals(number)){
				curcol = coltypeService.findEntityById(colid);
				//查看当前栏目是否存在
				if(curcol==null)
					return;
				curcol = coltypeService.findEntityByNumer(curcol.getPnumber(), siteid);
			}else{
				curcol = coltypeService.findEntityByNumer(number, siteid);
			}
			//查看要显示的栏目是否存在
			if(curcol==null)
				return;
			if("colname".equals(field))
				outWrite(curcol.getColname());
			else if("vurl".equals(field))
				outWrite(WebUtil.webUrl(request)+"/pub/col"+curcol.getVurl());
			else if("microimgurl".equals(field)){
				//查询栏目缩略图
				ColfileDto fileDto = new ColfileDto();
				fileDto.setRelatiovalue(NimsenConstant.FILE_RELATION_MICROIMG);
				fileDto.setColtypeid(curcol.getId());
				List<Map<String, Object>> micromigs = colfileService.findTagFileByDto(fileDto);
				if(!CollectionUtils.isEmpty(micromigs)){
					Map<String, Object> microimg = micromigs.get(0);
					outWrite(NimsenUtil.obj2String(microimg.get("filename")));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
